import { fileURLToPath } from 'url'
import fs from 'fs'

// 获取所有控制器文件的路径
export function getControllers() {
  // 获取文件路径
  let controllerUrl = new URL('../controllers', import.meta.url).href
  let controllerPath = fileURLToPath(controllerUrl)
  // console.log(controllerPath);

  // 读取文件
  let file = fs.readdirSync(controllerPath).filter(item => item.endsWith('Controller.js'))
  let filePath = file.map(item => controllerUrl + '/' + item)
  // console.log(filePath);

  return filePath
}


// 注册路由
export function regControllers(router, controllerFiles) {
  if (controllerFiles == null) {
    return null
  }
  controllerFiles.forEach(async item => {
    // 动态导入模块
    let { default: arr } = await import(item)

    // 遍历
    arr.forEach(obj => {
      if (obj.method === 'get') {
        router.get(obj.url, obj.fn)
      }
      if (obj.method === 'post') {
        router.post(obj.url, obj.fn)
      }
      if (obj.method === 'put') {
        router.put(obj.url, obj.fn)
      }
      if (obj.method === 'delete') {
        router.delete(obj.url, obj.fn)
      }
    })
  });
}